const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const P2PDownloader = require('./downloader/P2PDownloader.cjs');

let mainWindow;
const downloaders = new Map();

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 900,
    minHeight: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.cjs')
    },
    autoHideMenuBar: true,
    backgroundColor: '#1a1a1a'
  });

  // 开发环境加载 Vite 开发服务器
  if (process.env.NODE_ENV === 'development' || !app.isPackaged) {
    mainWindow.loadURL('http://localhost:5173');
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
  }
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// IPC 处理器
ipcMain.handle('dialog:selectSavePath', async (event, defaultName) => {
  const result = await dialog.showSaveDialog(mainWindow, {
    title: '选择保存位置',
    defaultPath: defaultName,
    properties: ['createDirectory']
  });
  return result.filePath;
});

ipcMain.handle('dialog:selectDirectory', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    title: '选择默认下载路径',
    properties: ['openDirectory', 'createDirectory']
  });
  return result.canceled ? null : result.filePaths[0];
});

ipcMain.handle('download:start', async (event, downloadConfig) => {
  try {
    const { id, type, url, savePath, peers, shardCount, rsConfig } = downloadConfig;
    
    console.log(`\n========== 开始下载任务 #${id} ==========`);
    console.log('配置:', JSON.stringify(downloadConfig, null, 2));
    
    const downloader = new P2PDownloader({
      id,
      url,
      savePath,
      peers: peers || [],
      shardCount: shardCount || 1,
      rsConfig,
      onProgress: (progress) => {
        console.log(`[任务 #${id}] 进度: ${progress.percentage.toFixed(1)}%`);
        mainWindow.webContents.send('download:progress', { id, progress });
      },
      onComplete: (result) => {
        console.log(`[任务 #${id}] ✅ 下载完成:`, result.path);
        mainWindow.webContents.send('download:complete', { id, result });
        downloaders.delete(id);
      },
      onError: (error) => {
        console.error(`[任务 #${id}] ❌ 下载失败:`, error.message);
        mainWindow.webContents.send('download:error', { id, error: error.message });
        downloaders.delete(id);
      }
    });

    downloaders.set(id, downloader);
    
    // 不要在这里等待，让它在后台运行
    downloader.start().catch(err => {
      console.error(`[任务 #${id}] 启动失败:`, err);
    });
    
    return { success: true, id };
  } catch (error) {
    console.error('下载启动失败:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('download:pause', async (event, id) => {
  const downloader = downloaders.get(id);
  if (downloader) {
    await downloader.pause();
    return { success: true };
  }
  return { success: false, error: '下载任务不存在' };
});

ipcMain.handle('download:resume', async (event, id) => {
  const downloader = downloaders.get(id);
  if (downloader) {
    await downloader.resume();
    return { success: true };
  }
  return { success: false, error: '下载任务不存在' };
});

ipcMain.handle('download:cancel', async (event, id) => {
  const downloader = downloaders.get(id);
  if (downloader) {
    await downloader.cancel();
    downloaders.delete(id);
    return { success: true };
  }
  return { success: false, error: '下载任务不存在' };
});

ipcMain.handle('download:parseLink', async (event, link) => {
  try {
    // 解析 P2P 下载链接
    // 格式示例: p2p://filename?peers=peer1,peer2&shards=100&rs=10,5
    const url = new URL(link);
    
    if (url.protocol !== 'p2p:') {
      throw new Error('不支持的协议，请使用 p2p:// 链接');
    }

    const filename = url.hostname || 'download';
    const peers = url.searchParams.get('peers')?.split(',') || [];
    const shardCount = parseInt(url.searchParams.get('shards') || '100');
    const rsParam = url.searchParams.get('rs');
    
    let rsConfig = null;
    if (rsParam) {
      const [dataShards, parityShards] = rsParam.split(',').map(Number);
      rsConfig = { dataShards, parityShards };
    }

    return {
      success: true,
      config: {
        filename,
        peers,
        shardCount,
        rsConfig
      }
    };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

